package com.yang.dao;

import java.sql.Connection;
import java.sql.SQLException;

import com.yang.entity.Student;
import com.yang.util.ConnectionFactory;
/**
 * 测试类
 * @author 杨吉明
 *
 */
public class Test {

	public static void main(String[] args) {
		ConnectionFactory factory = ConnectionFactory.getInstance();
		Connection conn = factory.getConnection();
		
		DealStudent deal = new DealStudent();
		try {
			//1、向数据表写入十条不同的数据，并将数据库中所有的数据输出
			insertData(deal, conn);
			System.out.println("============insert into t_students success============");
			deal.queryAll(conn);
			System.out.println("============query all data from t_students success============");
			
			//2、查询年龄大于15岁的男生，并将数据输出 
			Student stu_query = new Student();
			stu_query.setAge(15);
			deal.queryByAge(conn, stu_query);
			System.out.println("============query data from t_students by age success============");
			
			//3、删除所有男生的数据，并将删除之后，数据库中的所有数据输出
			Student stu_del = new Student();
			stu_del.setGender(1);//男
			deal.delete(conn, stu_del);
			System.out.println("============delete data from t_students success============");
			deal.queryAll(conn);
			System.out.println("============query all data from t_students success============");
			
		} catch (SQLException e) {
			System.out.println("deal data fail");
			e.printStackTrace();
		}finally{
			factory.close(null, null, conn);
		}
	}
	
	/**
	 * 插入数据
	 * @param deal
	 * @param conn
	 * @throws SQLException
	 */
	public static void insertData(DealStudent deal,Connection conn) {
		try {
			conn.setAutoCommit(false);
			//新增数据之前删除所有数据
			deal.deleteAll(conn);
			//插入数据
			Student stu1 = new Student(1, "王庆", 14, 1, "北京");
			deal.insert(conn, stu1);
			Student stu2 = new Student(2, "王笑", 13, 0, "山东");
			deal.insert(conn, stu2);
			Student stu3 = new Student(3, "李芳", 16, 0, "河北");
			deal.insert(conn, stu3);
			Student stu4 = new Student(4, "刘华", 18, 1, "北京");
			deal.insert(conn, stu4);
			Student stu5 = new Student(5, "杨港", 22, 1, "重庆");
			deal.insert(conn, stu5);
			Student stu6 = new Student(6, "李蕊", 17, 0, "深圳");
			deal.insert(conn, stu6);
			Student stu7 = new Student(7, "赵云", 25, 1, "广东");
			deal.insert(conn, stu7);
			Student stu8 = new Student(8, "李慧", 22, 0, "北京");
			deal.insert(conn, stu8);
			Student stu9 = new Student(9, "李遂", 12, 1, "湖南");
			deal.insert(conn, stu9);
			Student stu10 = new Student(10, "高欣", 15, 0, "北京");
			deal.insert(conn, stu10);
			//事务提交
			conn.commit();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			System.out.println("新增数据失败");
		}
	}
}
